﻿
using NP.BPMReportPlatform.AUTO;
using NP.BPMReportPlatform.AUTO.Adjust.Dto;
using NP.BPMReportPlatform.AUTO.Quotation.Dto;
using NP.BPMReportPlatform.AUTO.TechnicalDependence.Dto;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Engine;
using NP.BPMReportPlatform.CommonEnum;
using NP.BPMReportPlatform.FlowManagement.Dto;
using NP.BPMReportPlatform.IC.ICZHYLS.Dto;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
namespace NP.BPMReportPlatform.IC
{
    public class ICSamplerAppService : BPMReportPlatformAppService, IICSamplerAppService
    {
        private readonly SqlSugarClient _db, _dbEngine;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;
        /// <summary>
        /// 
        public ICSamplerAppService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp, IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbEngine = sqlSugarAppService.GetEngineInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        #region  
        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<ICSamplerOutput> GetQueryable(GetICSamplerInput input)
        {

            var listQueryable = _db.Queryable<ICSampleRequestHeader, BusinessProcessesNew, ICSampleRequestDetail>(
                    (x, bu, m) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == bu.InstanceId, JoinType.Left, x.InstanceNumber == m.InstanceNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    (x, bu) => x.InstanceNumber.Contains(input.InstanceNumber))

                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Equals(input.AddUserName))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AssistantName), x => x.AssistantName.Equals(input.AssistantName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AssistantID), x => x.AssistantID.Equals(input.AssistantID))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), x => x.CustomerName.Contains(input.CustomerName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ToUsers), x => x.ToUsers.Contains(input.ToUsers))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProjectType), x => x.ProjectType.Equals(input.ProjectType))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime.AddDays(-1) <= input.EndCreationTime)

                .Select((x, bu, m) =>
                    new ICSamplerOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        AssistantName = x.AssistantName,
                        AssistantID = x.AssistantID,
                        ToUsers = x.ToUsers,
                        ProjectType = x.ProjectType,
                        CustomerName = x.CustomerName,
                        CustomerNo = x.CustomerNo,
                        OrderStatus = bu.ProcessStatusName,
                        CreateTime = bu.StartTime.ToString(),
                        UserName = bu.StartUserName,

                    }).MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);

            return listQueryable;
        }


        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<ICSamplerOutput>> GetAllAsync(GetICSamplerInput input)
        {
           // await UpdateOrderStatus(input);
            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);

            });



            //返回结果
            return new PagedResultDto<ICSamplerOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }




        #endregion


        #region IC样品导出GetQueryableExport1

        private ISugarQueryable<ExportICSamplerOutput> GetQueryableExport1(GetICSamplerInput input)
        {

            var listQueryable = _db.Queryable<ICSampleRequestHeader, BusinessProcessesNew, ICSampleRequestDetail>(
              (x, bu, d1) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == bu.InstanceId,
              JoinType.Left, x.InstanceNumber == d1.InstanceNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),(x, bu) => x.InstanceNumber.Contains(input.InstanceNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Equals(input.AddUserName))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AssistantName), x => x.AssistantName.Equals(input.AssistantName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AssistantID), x => x.AssistantID.Equals(input.AssistantID))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), x => x.CustomerName.Contains(input.CustomerName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ToUsers), x => x.ToUsers.Contains(input.ToUsers))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProjectType), x => x.ProjectType.Equals(input.ProjectType))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime.AddDays(-1) <= input.EndCreationTime)
                .Select((x, bu, d1) =>
                    new ExportICSamplerOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        MFDDstatus = x.MFDDstatus,
                        WLstatus = x.WLstatus,
                        RequirementType = x.RequirementType,
                        ClientType = x.ClientType,
                        SalesPM = x.SalesPM,
                        userOrganization = x.userOrganization,
                        BusinessOpportunities = x.BusinessOpportunities,
                        AssistantID = x.AssistantID,
                        ProductCompanyCode = x.ProductCompanyCode,
                        DeliveryAddress = x.DeliveryAddress,
                        DeliveryNO1 = x.DeliveryNO1,
                        CustomerNo = x.CustomerNo,
                        CustomerName = x.CustomerName,
                        AssistantName = x.AssistantName,
                        CustomType = x.CustomType,
                        CustomGS = x.CustomGS,
                        SalesDept1 = x.SalesDept1,
                        CustomerRank = x.CustomerRank,
                        CrmProjectName = x.CrmProjectName,
                        ProjectType = x.ProjectType,
                        AapplyDate = x.AapplyDate,
                        TSnumber = x.TSnumber,
                        HandPerson = x.HandPerson,
                        ToUsers = x.ToUsers,
                        ToUsersType = x.ToUsersType,
                        Receiver = x.Receiver,
                        ReceiverTel = x.ReceiverTel,
                        ToUsersAear = x.ToUsersAear,
                        ToUsersAddress = x.ToUsersAddress,
                        Suggest = x.Suggest,
                        JFRYName = x.JFRYName,
                        ccUsersName = x.ccUsersName,
                        ModifyBy = d1.ModifyBy,
                        ProductNo = d1.ProductNo,
                        ProductName = d1.ProductName,
                        ProductXL = d1.ProductXL,
                        ProductNetWeight = d1.ProductNetWeight,
                        ProductNumber = d1.ProductNumber,
                        ProductWeight = d1.ProductWeight,
                        APrice = d1.APrice,
                        Cost = d1.Cost,
                        TotalCost = d1.TotalCost,
                        Factory = d1.Factory,
                        Stock = d1.Stock,
                        OrderStatus = bu.ProcessStatusName,
                        CreateTime = bu.StartTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        UserName = bu.StartUserName,
                        //LatelyActivityName = bu.LatelyActivityName,
                        FinishTime = bu.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),


                    }).MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);

            return listQueryable;
        }

        #endregion

        #region IC样品导出Export1Async
        /// <summary>
        /// 报表导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<ExportICSamplerOutput>> Export1Async(GetICSamplerInput input)
        {
            ////await UpdateOrderStatus(input);
            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryableExport1(input);
            var listViewDto = await listQueryable.ToListAsync();
            //var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);



            var i = 1;
            listViewDto.ForEach(x => x.SerialNumber = i++.ToString());
            return listViewDto;
        }

        #endregion
    }
}
